package com.elinkway.infinitemovies.selfdata.dao;

import android.content.Context;
import android.text.TextUtils;

import com.elinkway.infinitemovies.selfdata.bean.MyDataRecord;

import io.realm.Realm;
import io.realm.RealmConfiguration;

/**
 * Created by zhaopeipei on 2017/7/7.
 */
public class RealmDaoManager {

    private static Realm realm;
    private static MyDataDao mDao;

    public static synchronized void init(Context context) {
        Realm.init(context);
        realm = getInstance();
    }

    public static synchronized void close() {
        if (realm != null) {
            realm.close();
        }
    }

    public static synchronized void init(Context context, String name) {
        Realm.init(context);
        getInstance(name);
    }

    public static synchronized Realm getInstance() {
        if (realm == null) {
            synchronized (RealmDaoManager.class) {
                if (realm == null) {
                    RealmConfiguration configuration = new RealmConfiguration.Builder()
                            .name("myDataDao.realm")
                            .build();
                    realm = Realm.getInstance(configuration);
                }
            }
        }
        return realm;
    }

    public static Realm getInstance(String name) {
        if (TextUtils.isEmpty(name)) {
            throw new NullPointerException();
        }
        if (realm == null) {
            synchronized (RealmDaoManager.class) {
                if (realm == null) {
                    RealmConfiguration configuration = new RealmConfiguration.Builder()
                            .name(name)
                            .build();
                    realm = Realm.getInstance(configuration);
                }
            }
        }
        return realm;
    }

    public static MyDataDao getMyDataDao(){
        if(mDao == null){
            synchronized (MyDataDao.class) {
                if (mDao == null) {
                    mDao = new MyDataDao();
                }
            }
        }
        return mDao;
    }

    public static void addMyDataRecord(MyDataRecord record){
        getMyDataDao();
        mDao.add(record);
    }
}
